<template>
  <div class="allocation-page">
    <!-- 顶部内容 -->
    <div class="page-header">
      <h2 style="margin-top: 0;">项目分配</h2>
      <p class="description">将项目分配给专家进行评审管理</p>
    </div>

    <!-- 全局筛选区 -->
    <div class="filter-section">
      <div class="filter-group">
        <span class="filter-label">专业组筛选：</span>
        <el-select
            v-model="currentSpecialty"
            placeholder="请选择专业组"
            @change="handleSpecialtyChange"
            class="specialty-select"
        >
          <!-- 移除"全部专业组"选项 -->
          <el-option label="油气勘探" value="油气勘探"></el-option>
          <el-option label="油气藏工程" value="油气藏工程"></el-option>
          <el-option label="钻采与地面工程" value="钻采与地面工程"></el-option>
          <el-option label="信息工程" value="信息工程"></el-option>
        </el-select>
      </div>
    </div>

    <!-- 操作区 -->
    <div class="operation-section">
      <el-button
          type="primary"
          @click="openProjectDialog"
          icon="el-icon-folder-add"
      >
        选择待分配项目
      </el-button>
      <el-button
          type="success"
          @click="openExpertDialog"
          icon="el-icon-user-add"
          :disabled="filteredAllocatedProjects.length === 0"
          style="margin-left: 15px;"
      >
        为项目分配评委
      </el-button>
      <el-button
          type="danger"
          @click="batchRemoveProjects"
          icon="el-icon-delete"
          :disabled="selectedAllocatedProjects.length === 0"
          style="margin-left: 15px;"
      >
        批量删除
      </el-button>
    </div>

    <!-- 已分配项目表格 -->
    <div class="allocated-section">
      <div class="allocated-header">
        <h3>已分配评审专家的项目列表</h3>
        <el-button
            type="primary"
            @click="saveAllocation"
            :disabled="!hasChanges"
            size="small"
        >
          <i v-if="isSaving" class="el-icon-loading"></i>
          保存分配结果
        </el-button>
      </div>

      <div class="allocated-table">
        <el-table
            :data="filteredAllocatedProjects"
            border
            size="small"
            v-loading="allocatedLoading"
            element-loading-text="正在加载已分配项目..."
            @selection-change="handleAllocatedSelectionChange"
            ref="allocatedTable"
        >
          <!-- 选择框 -->
          <el-table-column
              type="selection"
              width="40">
          </el-table-column>

          <!-- 序号 -->
          <el-table-column
              type="index"
              label="序号"
              width="60">
          </el-table-column>

          <!-- 项目名称 -->
          <el-table-column
              prop="projectName"
              label="项目名称"
              width="200"
              show-overflow-tooltip>
          </el-table-column>

          <!-- 专业组 -->
          <el-table-column
              prop="specialty"
              label="专业组"
              width="120">
          </el-table-column>

          <!-- 项目类型 -->
          <el-table-column
              prop="type"
              label="项目类型"
              width="120">
          </el-table-column>

          <!-- 申报等级 -->
          <el-table-column
              prop="declareLevel"
              label="申报等级"
              width="100">
            <template slot-scope="scope">
              <el-tag :type="getLevelTagType(scope.row.declareLevel)">
                {{ scope.row.declareLevel }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 评审专家 -->
          <el-table-column
              label="评审专家"
              min-width="300">
            <template slot-scope="scope">
              <div class="expert-tags">
                <el-tag
                    type="info"
                    size="mini"
                    closable
                    @close="removeExpertFromProject(scope.row, expert)"
                    v-for="expert in scope.row.experts"
                    :key="expert.id"
                >
                  {{ expert.name }}
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <!-- 操作 -->
          <el-table-column
              label="操作"
              width="180">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="editProjectAllocation(scope.row)">
                更改评委
              </el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  style="color: #ff4d4f;"
                  @click="removeProject(scope.row)">
                移除项目
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空状态 -->
        <div v-if="filteredAllocatedProjects.length === 0 && !allocatedLoading" class="allocated-empty">
          <el-empty description="暂无已分配评审专家的项目"></el-empty>
        </div>
      </div>
    </div>

    <!-- 选择待分配项目对话框 -->
    <el-dialog
        title="选择待分配项目"
        :visible.sync="projectDialogVisible"
        width="1000px"
        :before-close="handleProjectDialogClose"
    >
      <!-- 项目选择对话框内容保持不变 -->
      <div class="dialog-content">
        <!-- 专业组名称 -->
        <div class="dialog-section">
          <strong>专业组：</strong>
          <span>{{ currentSpecialty }}</span>
        </div>

        <!-- 项目表格 -->
        <div class="dialog-table">
          <el-table
              :data="remoteProjects"
              border
              minwidth="1100"
              ref="dialogProjectTable"
              @selection-change="handleDialogProjectSelectionChange"
              height="400"
              size="small"
              v-loading="projectLoading"
          >
            <el-table-column
                type="selection"
                width="40">
            </el-table-column>
            <el-table-column
                type="index"
                label="序号"
                width="60">
            </el-table-column>
            <el-table-column
                prop="projectName"
                label="项目名称"
                show-overflow-tooltip>
            </el-table-column>
            <el-table-column
                prop="specialty"
                label="专业组"
                width="120">
            </el-table-column>
            <el-table-column
                prop="year"
                label="年度"
                width="60">
            </el-table-column>
            <el-table-column
                prop="type"
                label="项目类型"
                width="120">
            </el-table-column>
            <el-table-column
                prop="declareLevel"
                label="申报等级"
                width="100">
              <template slot-scope="scope">
                <el-tag :type="getLevelTagType(scope.row.declareLevel)">
                  {{ scope.row.declareLevel }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页控件 -->
          <el-pagination
              @size-change="handleProjectSizeChange"
              @current-change="handleProjectCurrentChange"
              :current-page="projectPageNum"
              :page-sizes="[10, 20, 50]"
              :page-size="projectPageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="projectTotal"
              style="margin-top: 15px; text-align: right;"
          ></el-pagination>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="projectDialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="confirmProjectSelection"
            :disabled="selectedDialogProjects.length === 0"
        >
          确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 为项目分配评委对话框 -->
    <el-dialog
        title="为项目分配评委"
        :visible.sync="expertDialogVisible"
        width="800px"
        :before-close="handleExpertDialogClose"
    >
      <div class="dialog-content">
        <!-- 专业组名称 -->
        <div class="dialog-section">
          <strong>专业组：</strong>
          <span>{{ currentSpecialty }}</span>
        </div>

        <!-- 选择项目（多选）及快捷选择 -->
        <div class="dialog-section">
          <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
            <el-select
                v-model="selectedProjectIds"
                placeholder="选择要分配的项目"
                class="project-select"
                multiple
                collapse-tags
                @change="handleProjectChange"
                style="flex: 1;"
            >
              <el-option
                  v-for="project in filteredAllocatedProjects"
                  :key="project.projectId"
                  :label="project.projectName"
                  :value="project.projectId"
              ></el-option>
            </el-select>

            <el-button
                type="text"
                size="mini"
                @click="selectAllProjects"
            >
              {{ isAllProjectsSelected ? '取消全选' : '全选' }}
            </el-button>
          </div>

          <!-- 提示信息 -->
          <el-alert
              v-if="showReplaceAlert"
              title="提示：选择的项目已有评委信息，确定后将被替换"
              type="warning"
              :closable="false"
              style="margin-top: 10px;"
          ></el-alert>
        </div>

        <!-- 专家表格 -->
        <div class="dialog-table">
          <el-table
              :data="filteredExpertsForDialog"
              border
              ref="dialogExpertTable"
              @selection-change="handleDialogExpertSelectionChange"
              size="small"
              v-loading="judgeLoading"
          >
            <el-table-column
                type="selection"
                width="40">
            </el-table-column>
            <el-table-column
                type="index"
                label="序号"
                width="60">
            </el-table-column>
            <el-table-column
                prop="name"
                label="专家名称"
                width="120">
            </el-table-column>
            <el-table-column
                prop="category"
                label="专家职务"
                width="150">
            </el-table-column>
            <el-table-column
                prop="contactInfo"
                label="联系方式"
                show-overflow-tooltip>
            </el-table-column>
            <el-table-column
                prop="review_count"
                label="评审次数"
                width="100">
              <template slot-scope="scope">
                {{ scope.row.review_count || 0 }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="expertDialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="confirmExpertSelection"
            :disabled="selectedDialogExperts.length === 0 || !selectedProjectIds || selectedProjectIds.length === 0"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入接口函数
import {getAwardPage} from '@/api/award';
import {getJudgesBySpecialty} from '@/api/judge';
import {batchDeleteScores, batchSaveScores, deleteScoreByAwardId, getAwardAllocatedExperts} from '@/api/score';

export default {
  data() {
    return {
      // 筛选条件 - 默认选择第一个专业组
      currentSpecialty: '油气勘探',
      previousSpecialty: '油气勘探', // 保存之前的专业组选择

      // 对话框状态
      projectDialogVisible: false,
      expertDialogVisible: false,
      selectedProjectIds: [], // 存储多个项目ID
      showReplaceAlert: false, // 是否显示替换提示
      isAllProjectsSelected: false, // 项目是否全选

      // 选择状态
      selectedDialogProjects: [],
      selectedDialogExperts: [],
      selectedAllocatedProjects: [], // 已选择的已分配项目

      // 远程数据相关
      remoteProjects: [], // 从接口获取的项目数据
      projectLoading: false, // 项目数据加载状态
      projectPageNum: 1, // 当前页码
      projectPageSize: 10, // 每页条数
      projectTotal: 0, // 总记录数

      // 专家数据
      experts: [], // 存储从API获取的专家数据
      judgeLoading: false, // 专家数据加载状态

      // 分配状态
      allocatedProjects: [],
      allocatedLoading: false, // 已分配项目加载状态

      // 状态标记
      hasChanges: false,
      isSaving: false,
      isDeleting: false // 删除操作状态
    };
  },

  computed: {
    // 待分配项目（排除已完成和已分配的）
    unallocatedProjects() {
      const allocatedIds = this.allocatedProjects.map(item => item.projectId);
      return this.remoteProjects.filter(project =>
          !allocatedIds.includes(project.id)
      );
    },

    // 对话框中筛选后的项目
    filteredProjectsForDialog() {
      return this.unallocatedProjects.filter(project =>
          project.specialty === this.currentSpecialty
      );
    },

    // 对话框中筛选后的专家
    filteredExpertsForDialog() {
      // 处理专家可能属于多个专业组的情况（用逗号分隔）
      return this.experts.filter(expert => {
        const specialties = expert.specialty ? expert.specialty.split(',') : [];
        return specialties.includes(this.currentSpecialty);
      });
    },

    // 筛选后的已分配项目
    filteredAllocatedProjects() {
      return this.allocatedProjects.filter(project =>
          (project.specialty?.trim() || '') === this.currentSpecialty
      );
    }
  },

  mounted() {
    // 组件挂载后加载已分配项目数据
    this.loadAllocatedProjects();
  },

  methods: {
    // 获取项目等级标签样式
    getLevelTagType(level) {
      const typeMap = {
        '一等奖': 'primary',
        '二等奖': 'success',
        '三等奖': 'info'
      };
      return typeMap[level] || 'default';
    },

    // 处理专业组筛选变化 - 添加未保存提示
    handleSpecialtyChange(newValue) {
      // 如果没有变化，不做处理
      if (newValue === this.previousSpecialty) return;

      // 如果有未保存的更改，提示用户
      if (this.hasChanges) {
        this.$confirm('检测到未保存的分配结果，切换专业组将丢失这些更改。是否继续？', '提示', {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 用户确认继续，执行切换逻辑
          this.doSpecialtyChange(newValue);
        }).catch(() => {
          // 用户取消，恢复之前的专业组选择
          this.$nextTick(() => {
            this.currentSpecialty = this.previousSpecialty;
          });
        });
      } else {
        // 没有未保存的更改，直接执行切换
        this.doSpecialtyChange(newValue);
      }
    },

    // 实际执行专业组切换的逻辑
    doSpecialtyChange(newValue) {
      // 保存当前专业组作为之前的专业组
      this.previousSpecialty = newValue;

      // 清空项目选择
      this.selectedProjectIds = [];
      this.isAllProjectsSelected = false;
      this.selectedAllocatedProjects = [];

      // 如果项目对话框已打开，重新加载数据
      if (this.projectDialogVisible) {
        this.loadProjectData();
      }

      // 重新加载已分配项目数据
      this.loadAllocatedProjects();
    },

    // 分页大小变化
    handleProjectSizeChange(val) {
      this.projectPageSize = val;
      this.projectPageNum = 1;
      this.loadProjectData();
    },

    // 当前页码变化
    handleProjectCurrentChange(val) {
      this.projectPageNum = val;
      this.loadProjectData();
    },

    // 加载项目数据
    loadProjectData() {
      this.projectLoading = true;

      // 构建查询参数
      const params = {
        pageNum: this.projectPageNum,
        pageSize: this.projectPageSize,
        filters: {
          specialty: this.currentSpecialty
        }
      };

      // 调用接口获取数据
      getAwardPage(params)
          .then(response => {
            this.remoteProjects = response.data.records || [];
            this.projectTotal = response.data.total || 0;
            this.projectLoading = false;
          })
          .catch(error => {
            console.error('获取项目数据失败:', error);
            this.$message.error('获取项目数据失败，请重试');
            this.projectLoading = false;
          });
    },

    // 加载已分配项目数据
    loadAllocatedProjects() {
      this.allocatedLoading = true;
      getAwardAllocatedExperts(this.currentSpecialty)
          .then(response => {
            // 适配接口返回格式到表格所需的allocatedProjects
            const apiData = response.data || [];
            this.allocatedProjects = apiData.map(item => ({
              projectId: item.awardId, // 映射奖项ID为项目ID
              projectName: item.projectName,
              specialty: item.specialty,
              type: item.type || '未分类',
              declareLevel: item.declareLevel || '无',
              // 转换专家格式：[{"1":"张雪坤"}] -> [{id:1, name:"张雪坤"}]
              experts: item.experts.map(expertObj => {
                const expertId = Object.keys(expertObj)[0];
                const expertName = expertObj[expertId];
                return {
                  id: Number(expertId),
                  name: expertName
                };
              })
            }));
          })
          .catch(error => {
            console.error('加载已分配项目数据失败:', error);
            this.$message.error('加载已分配项目失败，请重试');
            this.allocatedProjects = [];
          })
          .finally(() => {
            this.allocatedLoading = false;
          });
    },

    // 加载专家数据
    loadJudgeData() {
      this.judgeLoading = true;
      this.experts = [];

      // 调用接口获取专家数据
      return getJudgesBySpecialty(this.currentSpecialty)
          .then(response => {
            this.experts = response.data || [];
            this.judgeLoading = false;
            return this.experts;
          })
          .catch(error => {
            console.error('获取专家数据失败:', error);
            this.$message.error('获取专家数据失败，请重试');
            this.judgeLoading = false;
            throw error;
          });
    },

    // 打开项目选择对话框
    openProjectDialog() {
      this.projectDialogVisible = true;
      this.selectedDialogProjects = [];
      this.projectPageNum = 1;

      // 重置表格选择并加载数据
      this.$nextTick(() => {
        if (this.$refs.dialogProjectTable) {
          this.$refs.dialogProjectTable.clearSelection();
        }
        this.loadProjectData();
      });
    },

    // 打开专家选择对话框
    openExpertDialog() {
      this.expertDialogVisible = true;
      this.selectedDialogExperts = [];
      this.selectedProjectIds = [];
      this.showReplaceAlert = false;
      this.isAllProjectsSelected = false;

      // 重置表格选择并加载专家数据
      this.$nextTick(() => {
        if (this.$refs.dialogExpertTable) {
          this.$refs.dialogExpertTable.clearSelection();
        }
        this.loadJudgeData();
      });
    },

    // 处理项目对话框关闭
    handleProjectDialogClose() {
      this.projectDialogVisible = false;
      this.selectedDialogProjects = [];
    },

    // 处理专家对话框关闭
    handleExpertDialogClose() {
      this.expertDialogVisible = false;
      this.selectedDialogExperts = [];
      this.selectedProjectIds = [];
      this.isAllProjectsSelected = false;
    },

    // 处理对话框中项目选择变化
    handleDialogProjectSelectionChange(selection) {
      this.selectedDialogProjects = selection;
    },

    // 处理对话框中专家选择变化
    handleDialogExpertSelectionChange(selection) {
      this.selectedDialogExperts = selection;
    },

    // 处理已分配项目的选择变化
    handleAllocatedSelectionChange(selection) {
      this.selectedAllocatedProjects = selection;
    },

    // 全选/取消全选项目
    selectAllProjects() {
      if (this.isAllProjectsSelected) {
        // 取消全选
        this.selectedProjectIds = [];
        this.isAllProjectsSelected = false;
      } else {
        // 全选所有项目
        this.selectedProjectIds = this.filteredAllocatedProjects.map(project => project.projectId);
        this.isAllProjectsSelected = true;
      }
      // 检查是否有项目已有专家信息，显示提示
      this.checkExistingExperts();
    },

    // 处理项目选择变化
    handleProjectChange() {
      this.selectedDialogExperts = [];
      if (this.$refs.dialogExpertTable) {
        this.$refs.dialogExpertTable.clearSelection();
      }

      // 更新全选状态
      this.isAllProjectsSelected = this.selectedProjectIds.length > 0 &&
          this.selectedProjectIds.length === this.filteredAllocatedProjects.length;

      // 检查是否有项目已有专家信息，显示提示
      this.checkExistingExperts();
    },

    // 检查选中的项目是否已有专家信息
    checkExistingExperts() {
      if (!this.selectedProjectIds || this.selectedProjectIds.length === 0) {
        this.showReplaceAlert = false;
        return;
      }

      // 检查选中的项目是否已有专家
      this.showReplaceAlert = this.selectedProjectIds.some(projectId => {
        const project = this.allocatedProjects.find(p => p.projectId === projectId);
        return project && project.experts && project.experts.length > 0;
      });
    },

    // 确认项目选择
    confirmProjectSelection() {
      if (this.selectedDialogProjects.length === 0) return;

      // 记录实际新增的数量
      let addedCount = 0;

      this.selectedDialogProjects.forEach(project => {
        // 检查项目是否已分配（防止重复）
        const existingIndex = this.allocatedProjects.findIndex(item => item.projectId === project.id);

        if (existingIndex === -1) {
          // 新分配
          this.allocatedProjects.push({
            projectId: project.id,
            projectName: project.projectName,
            specialty: project.specialty,
            type: project.type,
            declareLevel: project.declareLevel,
            experts: []
          });

          this.hasChanges = true;

          // 添加项目逻辑...
          addedCount++;
        }
      });

      this.$message.success(`已成功添加 ${addedCount} 个新项目到待分配列表（${this.selectedDialogProjects.length - addedCount} 个项目已存在）`);
      //this.$message.success(`已添加 ${this.selectedDialogProjects.length} 个项目到待分配列表`);
      this.projectDialogVisible = false;
      this.selectedDialogProjects = [];
    },

    // 确认专家选择
    confirmExpertSelection() {
      if (this.selectedDialogExperts.length === 0 || !this.selectedProjectIds || this.selectedProjectIds.length === 0) return;

      // 获取目标项目
      const targetProjects = this.allocatedProjects.filter(project =>
          this.selectedProjectIds.includes(project.projectId)
      );

      // 替换选中项目的专家
      targetProjects.forEach(project => {
        const projectIndex = this.allocatedProjects.findIndex(p => p.projectId === project.projectId);
        if (projectIndex > -1) {
          this.allocatedProjects[projectIndex].experts = this.selectedDialogExperts.map(expert => ({
            id: expert.id,
            name: expert.name
          }));
          this.hasChanges = true;
        }
      });

      this.$message.success(`已为 ${targetProjects.length} 个项目分配 ${this.selectedDialogExperts.length} 位专家`);
      this.expertDialogVisible = false;
      this.selectedDialogExperts = [];
      this.selectedProjectIds = [];
      this.isAllProjectsSelected = false;
    },

    // 从项目中移除单个专家
    removeExpertFromProject(project, expert) {
      const projectIndex = this.allocatedProjects.findIndex(p => p.projectId === project.projectId);
      if (projectIndex > -1) {
        const expertIndex = this.allocatedProjects[projectIndex].experts.findIndex(e => e.id === expert.id);
        if (expertIndex > -1) {
          this.allocatedProjects[projectIndex].experts.splice(expertIndex, 1);
          this.hasChanges = true;
          this.$message.success(`已从项目中移除专家 ${expert.name}`);
        }
      }
    },

    // 编辑项目分配（更改专家）
    editProjectAllocation(project) {
      // 打开专家分配对话框并选中该项目
      this.selectedProjectIds = [project.projectId];
      this.isAllProjectsSelected = false;
      this.expertDialogVisible = true;

      // 加载专家数据并选中当前已有的专家
      this.loadJudgeData()
          .then(() => {
            this.$nextTick(() => {
              if (this.$refs.dialogExpertTable && project.experts && project.experts.length > 0) {
                this.experts.forEach(expert => {
                  if (project.experts.some(e => e.id === expert.id)) {
                    this.$refs.dialogExpertTable.toggleRowSelection(expert, true);
                  }
                });
                // 同步选择的专家
                this.selectedDialogExperts = this.experts.filter(expert =>
                    project.experts.some(e => e.id === expert.id)
                );
              }
            });
          });
    },

    // 检查项目是否已有评分
    hasProjectScores(project) {
      // 假设如果专家数组存在且有评分状态表示已有评分
      // 实际判断逻辑可能需要根据您的业务需求调整
      return project.experts && project.experts.length > 0;
    },

    // 移除单个项目（调用删除接口）
    removeProject(project) {
      // 检查是否有未保存的变更
      if (this.hasChanges) {
        this.$message.warning('存在未保存的分配变更，请先保存后再执行删除操作');
        return;
      }

      // 判断项目是否已有评分
      const hasScores = this.hasProjectScores(project);

      // 根据是否有评分显示不同的提示信息
      const confirmMessage = hasScores
          ? `项目"${project.projectName}"已分配评委，删除操作将同时清除所有相关的评分信息。\n\n确定要删除吗?`
          : `确定要删除项目"${project.projectName}"吗?`;

      this.$confirm(confirmMessage, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.isDeleting = true;
        // 调用删除接口
        deleteScoreByAwardId(project.projectId)
            .then(response => {
              this.isDeleting = false;
              this.$message.success('项目删除成功');
              // 刷新已分配项目列表
              this.loadAllocatedProjects();
              // 清空选择
              this.selectedAllocatedProjects = [];
              if (this.$refs.allocatedTable) {
                this.$refs.allocatedTable.clearSelection();
              }
              this.hasChanges = false;
            })
            .catch(error => {
              this.isDeleting = false;
              console.error('删除项目失败:', error);
              this.$message.error('删除项目失败，请重试');
            });
      }).catch(() => {
        // 取消操作
      });
    },

    // 批量删除项目
    batchRemoveProjects() {
      if (this.selectedAllocatedProjects.length === 0) return;

      // 检查是否有未保存的变更
      if (this.hasChanges) {
        this.$message.warning('存在未保存的分配变更，请先保存后再执行批量删除操作');
        return;
      }

      const projectNames = this.selectedAllocatedProjects.map(p => p.projectName).join('、');
      const projectIds = this.selectedAllocatedProjects.map(p => p.projectId);

      // 检查是否有项目已有评分
      const hasProjectsWithScores = this.selectedAllocatedProjects.some(project =>
          this.hasProjectScores(project)
      );

      // 根据是否有评分显示不同的提示信息
      const confirmMessage = hasProjectsWithScores
          ? `您选择的部分项目已分配评委并可能存在评分数据，批量删除操作将同时清除所有相关的评分信息。\n\n选中的项目：${projectNames}\n\n确定要批量删除吗?`
          : `确定要批量删除以下项目吗?\n${projectNames}`;

      this.$confirm(confirmMessage, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.isDeleting = true;
        // 调用批量删除接口
        batchDeleteScores(projectIds)
            .then(response => {
              this.isDeleting = false;
              this.$message.success(`已成功删除 ${this.selectedAllocatedProjects.length} 个项目`);
              // 刷新已分配项目列表
              this.loadAllocatedProjects();
              // 清空选择
              this.selectedAllocatedProjects = [];
              if (this.$refs.allocatedTable) {
                this.$refs.allocatedTable.clearSelection();
              }
              this.hasChanges = false;
            })
            .catch(error => {
              this.isDeleting = false;
              console.error('批量删除项目失败:', error);
              this.$message.error('批量删除项目失败，请重试');
            });
      }).catch(() => {
        // 取消操作
      });
    },

    // 保存分配结果
    saveAllocation() {
      // 检查是否有未分配评委的项目
      const projectsWithoutExperts = this.allocatedProjects.filter(
          project => project.experts.length === 0
      );

      // 如果存在未分配评委的项目，显示提醒
      if (projectsWithoutExperts.length > 0) {
        // 构建未分配评委的项目列表信息
        const projectNames = projectsWithoutExperts
            .map(p => p.projectName)
            .join('、');

        this.$confirm(
            `以下项目尚未分配评委：\n${projectNames}\n\n是否继续保存？未分配评委的项目将不会被保存。`,
            '提示',
            {
              confirmButtonText: '继续保存',
              cancelButtonText: '取消',
              type: 'warning'
            }
        ).then(() => {
          // 用户确认继续，执行保存逻辑（过滤掉未分配评委的项目）
          this.performSave(true);
        }).catch(() => {
          // 用户取消保存
          this.$message.info('已取消保存');
        });
        return;
      }

      // 如果所有项目都已分配评委，直接执行保存
      this.performSave(false);
    },

    // 实际执行保存的逻辑
    performSave(skipEmptyProjects) {
      this.isSaving = true;

      // 构建符合接口要求的评分列表数据
      const scoreList = [];

      this.allocatedProjects.forEach(project => {
        // 如果需要跳过未分配评委的项目，则直接 continue
        if (skipEmptyProjects && (!project.experts || project.experts.length === 0)) {
          return;
        }

        if (project.experts && project.experts.length > 0) {
          // 为每个专家创建一条记录
          project.experts.forEach(expert => {
            scoreList.push({
              awardId: project.projectId,
              expertId: expert.id,
              bgScore: null,
              innovationScore: null,
              economicScore: null,
              scoreStatus: 0,
              scoreRemark: ''
            });
          });
        }
      });

      // 检查是否有需要保存的数据
      if (scoreList.length === 0) {
        this.isSaving = false;
        this.$message.warning('没有需要保存的分配信息');
        return;
      }

      // 调用批量保存API
      batchSaveScores(scoreList)
          .then(response => {
            this.isSaving = false;
            this.hasChanges = false;
            this.$message.success('分配结果已成功保存到服务器');
            // 保存成功后重新加载数据，确保数据同步
            this.loadAllocatedProjects();
          })
          .catch(error => {
            this.isSaving = false;
            console.error('保存分配结果失败:', error);
            if (error.response && error.response.data && error.response.data.msg) {
              this.$message.error(`保存失败：${error.response.data.msg}`);
            } else {
              this.$message.error('保存分配结果失败，请重试');
            }
          });
    }
  }
};
</script>

<style>
.allocation-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 25px;
}

.description {
  color: #86909c;
  margin-bottom: 0;
}

/* 筛选区域样式 */
.filter-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 15px;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
}

.filter-label {
  color: #4e5969;
  margin-right: 8px;
  white-space: nowrap;
}

.specialty-select {
  width: 180px;
}

/* 操作区样式 */
.operation-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

/* 待分配项目区域 */
.allocated-section {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  padding: 15px;
}

.allocated-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.allocated-header h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
}

.allocated-table {
  width: 100%;
}

.expert-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.allocated-empty {
  padding: 40px 0;
}

/* 对话框样式 */
.dialog-content {
  padding: 10px 0;
}

.dialog-section {
  margin-bottom: 15px;
}

.year-select {
  width: 150px;
}

.project-select {
  width: 100%;
  max-width: 600px;
}

.dialog-table {
  margin-top: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .operation-section {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .operation-section el-button {
    width: 100%;
    margin-left: 0 !important;
  }

  .project-select {
    width: 100%;
  }
}
</style>
